#!/bin/sh

wait_services_available() {
  notrace_function traceable_wait_services_available "$@"
}

traceable_wait_services_available() {
  local NAMESPACE_OPT="$([ -z "$1" ] && printf "%s" "--all-namespaces" || printf "%s" "--namespace=$1")"
  local EXPECTED_AVAILABLE_SERVICES="${2:-1}"
  local EXPECTED_AVAILABLE_SERVICES_EXPRESSION="${3:-.*}"
  if ! [ "$EXPECTED_AVAILABLE_SERVICES" -ge 1 ] 2>/dev/null
  then
    >&2 echo "Must specify a number of expected available services of 1 or more or a grep regular expression that identify expected available service names"
    return 1
  fi
  local END="$(( $(date +%s) + (E2E_TIMEOUT * EXPECTED_AVAILABLE_SERVICES) ))"
  local SERVICES
  local AVAILABLE_SERVICES
  while [ "$(date +%s)" -lt "$END" ]
  do
    ENDPOINTS="$(kubectl get endpoints "$NAMESPACE_OPT" \
      --template '{{ range .items }}{{ $name := .metadata.name }}{{ with .subsets }}{{ range . }}{{ with .addresses }}{{ range . }}{{ printf "%s\n" $name }}{{ end }}{{ end }}{{ end }}{{ end }}{{ end }}' 2>/dev/null)"
    AVAILABLE_SERVICES="$(printf "%s" "$ENDPOINTS" \
      | grep "$EXPECTED_AVAILABLE_SERVICES_EXPRESSION" \
      | sort | uniq | tr '\n[:blank:]' ' -' | wc -w)"
    if [ "$AVAILABLE_SERVICES" -ge "$EXPECTED_AVAILABLE_SERVICES" ]
    then
      if [ -z "$1" ]
      then
        if [ -z "$3" ]
        then
          echo "All services available"
        else
          echo "All services available with regexp $EXPECTED_AVAILABLE_SERVICES_EXPRESSION"
        fi
      else
        if [ -z "$3" ]
        then
          echo "All services available in namespace $1"
        else
          echo "All services available in namespace $1 with regexp $EXPECTED_AVAILABLE_SERVICES_EXPRESSION"
        fi
       fi
      return
    fi
    sleep 2
  done
  if [ -z "$1" ]
  then
    if [ -z "$3" ]
    then
      echo "Timeout while waiting for all services to become available"
    else
      echo "Timeout while waiting for all services to become available with regexp $EXPECTED_AVAILABLE_SERVICES_EXPRESSION"
    fi
  else
  if [ -z "$3" ]
  then
      echo "Timeout while waiting for all services to become available in namespace $1"
    else
      echo "Timeout while waiting for all services to become available in namespace $1 with regexp $EXPECTED_AVAILABLE_SERVICES_EXPRESSION"
    fi
  fi
  echo
  kubectl describe services "$NAMESPACE_OPT" \
    | grep "$EXPECTED_AVAILABLE_SERVICES_EXPRESSION"
  return 1
}
